package com.he.strategy.impl;

import com.google.gson.Gson;
import com.he.config.properties.OssProperties;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author He
 * @version 1.0
 * @Date 2023/9/13 20:38
 * @Desc  七牛云OSS上传策略
 */
@Service("ossUploadStrategyImpl")
public class OssUploadStrategyImpl extends AbstractUploadStrategyImpl{

    @Resource
    private OssProperties ossProperties;

    @Resource
    private UploadManager uploadManager;

    @Resource
    private BucketManager bucketManager;


    //简单上传模式的凭证
    public String getUpToken() {
        return ossProperties.auth().uploadToken(ossProperties.getBucketName());
    }

    //覆盖上传模式的凭证
    public String getUpToken(String fileKey) {
        return ossProperties.auth().uploadToken(ossProperties.getBucketName(), fileKey);
    }

    /**
     * 判断服务器上是否存在该文件
    * */
    @Override
    public Boolean exists(String filePath) {
        try {
            bucketManager.stat(ossProperties.getBucketName(), filePath);
            System.out.println("文件存在");
            return true;
        } catch (Exception e) {
            System.out.println("文件不存在");
            return false;
        }
    }


    /**
     * 上传
     *
     * @param path        路径
     * @param fileName    文件名
     * @param inputStream 输入流
     * @throws IOException io异常
     */
    @Override
    public void upload(String path, String fileName, InputStream inputStream) throws IOException {
        try {
            String key = path + fileName;
            //采用简单上传模式的凭证,采用默认策略，
            Response response = uploadManager.put(inputStream, key, getUpToken(), null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        }
    }


    /**
     * 获取文件访问url
     *
     * @param filePath 文件路径
     * @return {@link String} 文件url
     */
    @Override
    public String getFileAccessUrl(String filePath) {
        return String.format("%s/%s", ossProperties.getUrl(), filePath);
    }
}
